import React from 'react';
import {Form, Row, Col, Button, DatePicker, message ,Divider,Modal,InputNumber,Input  } from 'antd';
import StatisticsBox from '../../components/box/statistics';
import {sessionManager} from '../../utils/sessionStorage';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import axios from 'axios';
import moment from 'moment';
import SCModal from '../../components/pickCity/SCModal';

const FormItem = Form.Item;
const createForm = Form.create;
const { TextArea } = Input;

const CustomizedForm = Form.create({
	onFieldsChange(props, changedFields) {
		console.log('onFieldsChange',props,changedFields)
		props.onChange((changedFields)=>{console.log('changedFields',changedFields)});
	},
	mapPropsToFields(props) {
		return {
			// username: Form.createFormField({
			// 	...props.username,
			// 	value: props.username.value,
			// }),
		};
	},
	onValuesChange(_, values) {
		console.log(values);
	},
})((props) => {
	const { getFieldDecorator } = props.form;
	return (
		<Form layout="inline" >
			<Row gutter={16}>
				<Col xl={12} xxl={12}>
					<FormItem label="调整电量">
						{getFieldDecorator('actualPower', {
							initialValue : 0
						})(<InputNumber  />)}
					</FormItem>
				</Col>
				<Col xl={12} xxl={12}>
					<FormItem label="实际电量">
						{getFieldDecorator('lastMoney', {
						})(<div>1111</div>)}
					</FormItem>
				</Col>
			</Row>
			<Row gutter={16}>
				<Col xl={12} xxl={12}>
					<FormItem label="调整金额">
						{getFieldDecorator('money', {
							initialValue : 0
						})(<InputNumber  />)}
					</FormItem>
				</Col>
				<Col xl={12} xxl={12}>
					<FormItem label="实际金额">
						{getFieldDecorator('lastMoney', {
						})(<div>11111</div>)}
					</FormItem>
				</Col>
			</Row>
			<FormItem label="调整原因">
				{getFieldDecorator('meg', {
				})(<TextArea rows={4} placeholder="请输入调整原因"/>)}
			</FormItem>
		</Form>
	);
});

class merchantAdjust extends React.Component {
	constructor(props) {
		super(props);
		this.common = this.props.intl.messages.common;
		this.columns = [
			{
				title: '调整时间',
				width: '120',
				dataIndex: 'createTime',
				key: 'createTime',
				// render: (text) => (
				// 	text.lastSettlementDate ? `${text.lastSettlementDate}-${text.settlementDate}` : `${text.settlementDate}`
				// )
			},
			{
				title: '调整电量（度）',
				dataIndex: 'actualPower',
				key: 'actualPower',
				width: '100',
			},
			{
				title: '实际电量（度）',
				dataIndex: 'settlementPower',
				key: 'settlementPower',
				width: '100',
			},
			{
				title: '调整金额（元）',
				dataIndex: 'money',
				key: 'money',
				width: '100',
			},
			{
				title: '实际金额（元）',
				dataIndex: 'settlementMoney',
				key: 'settlementMoney',
				width: '100',
			},
			{
				title: '调整原因',
				dataIndex: 'info',
				key: 'info',
				width: '200',
			}
		];
		this.state = {
			params:{
				id:'',
				settlementPower:'',
				settlementMoney:''
			},
			selectTime: moment().format('YYYY.MM.DD 23:59:59'),
			summary: [],
			visible: false,
			refresh:0,
			lastPower:'',
			lastMoney:''
		}
	}

	componentWillMount() {
		let newParams;
		if(this.props.location.state&&this.props.location.state.rowRecord){
			newParams = {
				id:this.props.location.state.rowRecord.id,
				settlementPower:this.props.location.state.rowRecord.settlementPower,
				settlementMoney:this.props.location.state.rowRecord.settlementMoney,
			}
		}else{
			newParams = {
				id:sessionManager.get('rowRecord').id||'',
				settlementPower:sessionManager.get('rowRecord').settlementPower||'',
				settlementMoney:sessionManager.get('rowRecord').settlementMoney||'',
			}
		}
		this.setState(Object.assign(this.state.params,newParams));
	}

	handleCancel = () => {
		this.setState({
			visible: false,
		})
	};
	showModal = () => {
		this.props.form.resetFields()
		this.setState({
			visible: true,
		});
	};
	changeAdjustNum = (value) => {
		console.log('changeVal',value)
	};
	adjustBill=(e)=>{
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((errors, values) => {
			if (!!errors) {
				return;
			}
			// console.info('Received values of form:',this.props.location.state.rowRecord,values);
			axios.get('/api/settlement/billSplit/addAdjust',{ params:{
					id:this.state.params.id,
					...values
				}}).then(res => {
				if(res&&res.code==200){
					this.freshGrid();
					this.handleCancel()
				}
			});
			// this.setState(Object.assign(this.state.params,values));

		});

		console.log('adjustBill,/api/settlement/billSplit/addAdjust')

	};
	freshGrid=()=>{
		this.setState({
			refresh:this.state.refresh+1
		})
	};
	goLink = (text, record, link) => {
		sessionManager.set('BillInfo', text);
		switch (link) {
			case 'BillDetails':
				this.props.history.push({pathname: '/finance/BillDetails'});
				break;
			case 'adjust':
				this.setState({
					visible: true,
				});
				console.log('adjust');
				break;
			default:
				this.props.history.push('/finance/orderDetails');
		}
	};

	// submitSettle = () => {
	// 	axios.post('/api/settlement/unSettled/submitSettle', {...{splitTime: this.state.totalData.splitTime}}).then(res => {
	// 		if (res && res.code == 200) {
	// 			if (res.data > 0) {
	// 				message.success('提交结算操作成功')
	// 			} else {
	// 				message.error('提交结算操作失败')
	// 			}
	// 		}
	// 	})
	// };

	getTotal = (date = this.state.selectTime) => {

	};

	endTimeLess = (rule, value, callback) => {

		if (value.isAfter(moment().format('YYYY.MM.DD'))) {
			callback(`请选择${moment().format('MM月DD日')}之前的时间`);
		} else {
			callback();
		}
	};

	transFormNull=(data)=>{
			for(let i=0;i<data.length;i++){
				if(!data[i].id){
					data[i].id=i
				}
			}
			return data
	}
	transformData=(data)=>{
		let newData = this.transFormNull(data.list);
		this.setState({
			lastMoney:data.lastMoney,
			lastPower:data.lastPower,
			summary: [
				{
					num: data.settlementPower,
					desc: '初次结算电量',
					// style:{width:400}
				},
				{
					num: data.settlementMoney,
					desc: '初次结算金额'
				},
				{
					num: [],
					actions: () => {
						return (
							<Button type="primary" onClick={this.showModal}>添加调整单</Button>
						)
					}
				}
			]
		});
		return newData;
	};
	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((errors, values) => {
			if (!!errors) {
				console.log('Errors in form!!!');
				return;
			}
			const newVal = {
				...values,
				orgId: values['orgId'].format('YYYY.MM.DD 23:59:59'),
			};
			console.log(newVal);
			this.getTotal(newVal['orgId']);
			this.setState({
				refresh:this.state.refresh+1
			})
		});
	}
	handleFormChange = (changedFields) => {
		this.setState({
			fields: { ...changedFields },
		});
	}
	render() {
		const {getFieldDecorator} = this.props.form;
		const dateFormat = 'YYYY.MM.DD';
		return (
			<div>
				{/*<form form={this.props.form}>
					<Row gutter={24} type="flex">
						<Col xl={5} xxl={3}>
							<FormItem
							>
								{getFieldDecorator('orgId', {
									rules: [{validator: this.endTimeLess}],
									initialValue: moment().subtract(1, 'days')
								})(
									<DatePicker format={dateFormat} allowClear={false}/>
								)}
							</FormItem>
						</Col>
						<Col span={4}>
							<FormItem>
								<Button type={'primary'} onClick={this.handleSubmit}>查询</Button>
							</FormItem>
						</Col>
					</Row>
				</form>*/}
				<StatisticsBox params={this.state.summary}/>
				<Grid url="api/settlement/billSplit/adjustList" columns={this.columns} refresh={this.state.refresh} params={this.state.params} transformData={this.transformData}/>
				<SCModal visible={this.state.visible } handleCancel={this.handleCancel} title='账单调整' footer={null} >
					<Form  onSubmit={this.adjustBill} className={"SC-form adjustForm"}>
						<Row gutter={16}>
							<Col xl={12} xxl={12}>
								<FormItem label="调整电量">
									{getFieldDecorator('actualPower', {
										initialValue : 0,
										rules: [{
											required: true,
											message: '请输入有效的调整值',
										},{
											pattern:/^[-]*\d{0,10}(\.\d{1,4})*$/,
											message:'最多4位小数,最大10位数'
										}]
									})(<InputNumber  />)}
								</FormItem>
							</Col>
							<Col xl={12} xxl={12}>
								<FormItem label="实际电量">
									{getFieldDecorator('lastPower', {
									})(<div>{this.state.lastPower}</div>)}
								</FormItem>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col xl={12} xxl={12}>
								<FormItem label="调整金额">
									{getFieldDecorator('money', {
										initialValue : 0,
										rules: [{
											required: true,
											message: '请输入有效的调整值',
										},{
											pattern:/^[-]*\d{0,10}(\.\d{1,4})*$/,
											message:'最多4位小数,最大10位数'
										}]
									})(<InputNumber  />)}
								</FormItem>
							</Col>
							<Col xl={12} xxl={12}>
								<FormItem label="实际金额">
									{getFieldDecorator('lastMoney', {
									})(<div>{this.state.lastMoney}</div>)}
								</FormItem>
							</Col>
						</Row>
						<FormItem label="调整原因">
							{getFieldDecorator('meg', {
								rules: [{
									required: true,
									message: '请输入有效的调整值',
								},{
									pattern:/^.{1,200}$/,
									message:'最多200字'
								}]
							})(<TextArea rows={4} placeholder="请输入调整原因"/>)}
						</FormItem>
						<div className="form-footer">
							<Button type={'default'} onClick={this.handleCancel}>取消</Button>
							<Button type={'primary'} htmlType="submit" className="ok-btn">确认调整</Button>
						</div>
					</Form>
					{/*<CustomizedForm onChange={this.handleFormChange}/>*/}
				</SCModal>
				{/*<AdjustHis visible={this.state.visible} handleCancel={this.handleCancel}/>*/}
			</div>
		)
	}
}

merchantAdjust = createForm()(merchantAdjust);
export default injectIntl(merchantAdjust)
